package priv.mill.controller;
import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import priv.mill.dao.model.UserT;

@Controller
@SessionAttributes(value={"user"}, types={String.class})
@RequestMapping("yuanSheng")
public class YuanShengController {

	private static final Logger logger = Logger
			.getLogger(YuanShengController.class);
	
	@ModelAttribute
	public void modelAtrribute(
			@RequestParam(value="id",required=false) Integer id
			,Map<String, Object> map){
		logger.debug("testModelAtrribute");
		
		if(id!=null){//当请求参数不为空的时候向Map中注入pojo
			UserT userT = new UserT();
			userT.setAge(88);
			userT.setUserName("modelAtrribute");
			map.put("userT", userT);
		}
	}
	
	@RequestMapping("/testModelAtrribute")
	public String testModelAtrribute(@ModelAttribute("userT") UserT user){
		logger.debug(user);
		return "yuansheng/session";
	}
	
	
	@RequestMapping("/testSession")
	public String testSession(Map<String, Object> map){
		UserT user = new UserT();
		user.setAge(88);
		user.setUserName("zhangsan");
		map.put("user", user);
		return "yuansheng/session";
	}
	
	
	/**
	 * 可以使用 Serlvet 原生的 API 作为目标方法的参数 具体支持以下类型
	 * 
	 * HttpServletRequest 
	 * HttpServletResponse 
	 * HttpSession
	 * java.security.Principal 
	 * Locale 
	 * InputStream 
	 * OutputStream 
	 * Reader 
	 * Writer
	 * @throws IOException 
	 */
	@RequestMapping("/testServletAPI")
	public void testServletAPI(HttpServletRequest request,
			HttpServletResponse response, Writer out) throws IOException {
		System.out.println("testServletAPI, " + request + ", " + response);
		out.write("hello springmvc");
	}
	
	/**
	 * 目标方法的返回值可以是 ModelAndView 类型。 
	 * 其中可以包含视图和模型信息
	 * SpringMVC 会把 ModelAndView 的 model 中数据放入到 request 域对象中. 
	 * @return
	 */
	@RequestMapping("/testModelAndView")
	public ModelAndView testModelAndView(){
		String viewName = "yuansheng/api";
		ModelAndView modelAndView = new ModelAndView(viewName);
		//添加模型数据到 ModelAndView 中.
		modelAndView.addObject("time", new Date());
		
		return modelAndView;
	}
	
	/**
	 * 目标方法可以添加 Map 类型(实际上也可以是 Model 类型或 ModelMap 类型)的参数. 
	 * @param map
	 * @return
	 */
	@RequestMapping("/testMap")
	public String testMap(Map<String, Object> map){
		System.out.println(map.getClass().getName()); 
		map.put("names", Arrays.asList("Tom", "Jerry", "Mike"));
		return "yuansheng/map";
	}
}
